#include "stm32f10x.h"
#include <stdint.h>
#include "TinyOS_Task.h"
#include "TinyOS_Delay.h"
#include "TinyOS_Timer.h"
#include "TinyOS_CpuTicks.h"
#include "TinyOS_Hook.h"
#include "app.h"

#if	TINYOS_ENABLE_TIMER == 1
void TimerTaskFunc(void *param)
{
    
    for(;;)
    {   
        TinyOS_SemaphoreTake(&TimerTickSem, 0);
        TinyOS_SemaphoreTake(&TimerProtectSem, 0);

        TinyOS_TimerHandleList(&TimerTaskList);
        
        TinyOS_SemaphoreGive(&TimerProtectSem);
    }    
}
#endif

void IdleTaskFunc(void* param)
{
	TinyOS_TaskSchedulerLockEnable();
	AppTaskInit();
	
#if	TINYOS_ENABLE_TIMER == 1
	TinyOS_TaskInit(
        &TimerTaskHandler, 
        TimerTaskFunc, 
        (void*)0x0, 
        TINYOS_TIMER_TASK_PRIORITY, 
        TimerTaskStack,
		TINYOS_TIMER_TASK_STACK
    );
#endif
	
	TinyOS_SetSystickPeriod(TINYOS_SYSTICK_PERIOD_MS);
		
# if TINYOS_ENABLE_CPUUSAGE == 1
	TinyOS_CpuUsageSyncWithSystick();
#endif
		
	for(;;)
	{
		uint32_t Stauts = TinyOS_TaskEnterCritical();       
		IdleTaskRunningCount++;	
		TinyOS_TaskExitCritical(Stauts);	
		
#if TINYOS_ENABLE_HOOK == 1
	TinyOS_HookCpuIdle();
#endif	
		
	}
}

int main()
{
	TinyOS_TaskSchedulerInit();
	TinyOS_TaskDelayedInit();
	
#if	TINYOS_ENABLE_TIMER == 1
    TinyOS_TimerModuleInit();
#endif
	
# if TINYOS_ENABLE_CPUUSAGE == 1	
	TinyOS_InitCpuUsageState();
#endif
	
	TinyOS_TickCountInit();
	
	TinyOS_TaskInit(
        &IdleTaskHandler, 
        IdleTaskFunc, 
        (void*)0x0, 
        TINYOS_TASK_PRIORITY_COUNT -1, 
        IdleTaskStack,
		TINYOS_IDLE_TASK_STACK
    );
    IdleTask = &IdleTaskHandler;

        
	NextTask = TinyOS_HighestPriTaskReady();
		
		
	TinyOS_TaskRunFisrt();
	
	
	return 0;
}
